package cn.cdeden.resource.service.impl;

import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.core.page.PageQuery;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.knowledge.api.domain.RemotePersonalTreeService;
import cn.cdeden.knowledge.api.domain.vo.RemotePersonalTreeVo;
import cn.cdeden.resource.domain.vo.SysOssRecentlyViewedVo;
import cn.cdeden.resource.domain.vo.SysOssVo;
import cn.cdeden.resource.unified.domain.dto.OnlinePreviewInfoDto;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import cn.cdeden.resource.domain.bo.SysOssRecentlyViewedBo;
import cn.cdeden.resource.domain.SysOssRecentlyViewed;
import cn.cdeden.resource.mapper.SysOssRecentlyViewedMapper;
import cn.cdeden.resource.service.ISysOssRecentlyViewedService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 文件最近查看Service业务层处理
 *
 * @author Yu.
 * @date 2024-12-09
 */
@RequiredArgsConstructor
@Service
public class SysOssRecentlyViewedServiceImpl implements ISysOssRecentlyViewedService {

    private final SysOssRecentlyViewedMapper baseMapper;


    @DubboReference(check = false)
    private RemotePersonalTreeService personalTreeService;


    private LambdaQueryWrapper<SysOssRecentlyViewed> buildQueryWrapper(SysOssRecentlyViewedBo bo, boolean isSelect) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOssRecentlyViewed> lqw = Wrappers.lambdaQuery(SysOssRecentlyViewed.class);
        lqw.eq(bo.getOssId() != null, SysOssRecentlyViewed::getOssId, bo.getOssId());
        lqw.eq(StringUtils.isNotBlank(bo.getModuleId()), SysOssRecentlyViewed::getModuleId, bo.getModuleId());
        lqw.eq(StringUtils.isNotBlank(bo.getModuleType()), SysOssRecentlyViewed::getModuleType, bo.getModuleType());
        lqw.eq(bo.getCreateBy() != null, SysOssRecentlyViewed::getCreateBy, bo.getCreateBy());
//        lqw.eq(bo.getViewedTime() != null, SysOssRecentlyViewed::getViewedTime, bo.getViewedTime());
//        lqw.eq(bo.getViewedNum() != null, SysOssRecentlyViewed::getViewedNum, bo.getViewedNum());
        lqw.orderByDesc(SysOssRecentlyViewed::getViewedTime);
        lqw.groupBy(isSelect, SysOssRecentlyViewed::getOssId); // 分组
        return lqw;
    }

    @Override
    public boolean save(SysOssVo sysOssVo, OnlinePreviewInfoDto info) {
        SysOssRecentlyViewed entity = new SysOssRecentlyViewed();
        entity.setOssId(sysOssVo.getOssId()); // ossId
        entity.setViewedTime(new Date());
        entity.setModuleId(info.getModuleId());
        entity.setVersionId(sysOssVo.getVersionId());
        entity.setVersionName(sysOssVo.getVersionName());
        entity.setModuleType(info.getType());
        entity.setViewedNum(1L);
        return baseMapper.insert(entity) > 0;
    }

    @Override
    public TableDataInfo<SysOssRecentlyViewedVo> selectRecordPage(SysOssRecentlyViewedBo bo, boolean isSelect, PageQuery pageQuery) {
//        LambdaQueryWrapper<SysOssRecentlyViewed> lqw = buildQueryWrapper(bo, isSelect); // 构建查询条件
//        IPage<SysOssRecentlyViewedVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        IPage<SysOssRecentlyViewedVo> page = baseMapper.selectPage(pageQuery.build(), isSelect, bo);
        List<SysOssRecentlyViewedVo> records = page.getRecords();

        if (isSelect) {
            Map<String, Set<String>> collect = records.stream().collect(
                Collectors.groupingBy(
                    SysOssRecentlyViewedVo::getModuleType,
                    Collectors.mapping(SysOssRecentlyViewedVo::getModuleId, Collectors.toSet())
                ));
            // 根据 moduleType 判断是否为个人模块
            if (collect.containsKey(OssModuleType.Personal.getCode())) {
                Set<String> personalIds = collect.get(OssModuleType.Personal.getCode());
                if (personalIds == null || personalIds.isEmpty()) {
//                    return; // 或者根据业务逻辑处理
                } else {
                    List<RemotePersonalTreeVo> fileNameSuffix = personalTreeService.getFileNameSuffix(new ArrayList<>(personalIds));
                    if (fileNameSuffix == null || fileNameSuffix.isEmpty()) {
//                    return; // 或者根据业务逻辑处理
                    } else {
                        // 使用 Map 提高查找效率
                        Map<Long, RemotePersonalTreeVo> treeVoMap = fileNameSuffix.stream()
                            .collect(Collectors.toMap(RemotePersonalTreeVo::getId, treeVo -> treeVo));

                        for (SysOssRecentlyViewedVo record : records) {
                            if (record.getModuleType().equals(OssModuleType.Personal.getCode())) {
                                Long moduleId = Long.parseLong(record.getModuleId());
                                if (treeVoMap.containsKey(moduleId)) {
                                    RemotePersonalTreeVo treeVo = treeVoMap.get(moduleId);
                                    record.setFileName(treeVo.getRealName());
                                    record.setFileSuffix(treeVo.getSuffix());
                                }
                            }
                        }
                    }

                }


            }

        }


        return TableDataInfo.build(page);
    }

    @Override
    public Boolean deleteViewedByModuleId(Collection<String> moduleId, OssModuleType type, boolean isDeleteFile, Collection<String> userIds) {
        LambdaQueryWrapper<SysOssRecentlyViewed> wrapper = Wrappers.lambdaQuery(SysOssRecentlyViewed.class)
            .in(!isDeleteFile, SysOssRecentlyViewed::getModuleId, moduleId)
            .in(isDeleteFile, SysOssRecentlyViewed::getOssId, moduleId)
            .eq(SysOssRecentlyViewed::getModuleType, type.getCode())
            .in(userIds!=null,SysOssRecentlyViewed::getCreateBy,userIds) // 根据创建人删除
            ;
        return baseMapper.delete(wrapper) > 0;
    }


}
